#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
#include<queue>
#include<unordered_map>
using namespace std;
class Solution {
public:
    vector<int> findOrder(int n, vector<vector<int>>& prerequisites) {
        unordered_map<int, vector<int>> aw;
        vector<int> as(n);
        vector<int> ret;
        for (auto& e : prerequisites)
        {
            int a = e[0], b = e[1];
            aw[b].push_back(a);
            as[a]++;
        }
        queue<int> q;
        for (int i = 0; i < n; i++)
        {
            if (as[i] == 0)
            {
                q.push(i);
            }
        }
        while (q.size())
        {
            int w = q.front();
            q.pop();
            ret.push_back(w);
            for (int a : aw[w])
            {
                as[a]--;
                if (as[a] == 0)
                {
                    q.push(a);
                }
            }
        }
        for (int i = 0; i < n; i++)
        {
            if (as[i] != 0)
            {
                return {};
            }
        }
        return ret;
    }
};